package ArithMathOperation;
//*************************************************************************************
//    RationalNumbers.java        Author:谭鑫
//
//    辅助产生真分数，分子小于分母。对第七章的RationalNumber进行小的改动。
//*************************************************************************************
public class RationalNumbers
{
       private int numerator, denominator;

        public RationalNumbers(int numer, int denom)
        {
            if (denom == 0)
                denom = 1;

            if (denom < 0)
            {
                numer = numer * -1;
                denom = denom * -1;
            }

            if (numer < denom)
            {
                numerator = numer;
                denominator = denom;
            }
            else
            {
                numerator = denom;
                denominator = numer;
            }
            reduce();
        }
        public String toString()
        {
            String result;
            if (numerator == 0)
                result = "0";
            else
            if (denominator == 1)
                result = numerator + "";
            else
                result = numerator + "/" + denominator;
            return result;
        }

        private void reduce()
        {
            if (numerator != 0)
            {
                int common = gcd(Math.abs(numerator), denominator);

                numerator = numerator / common;
                denominator = denominator / common;
            }
        }

        private int gcd(int num1,int num2)
        {
            while (num1 != num2)
                if (num1 > num2)
                    num1 = num1 - num2;
                else
                    num2 = num2 - num1;

            return num1;
        }
    }

